<template>
	<view>
		<!-- 上传图片多个 -->
		<u-upload v-if="!echo" :fileList="fileList" :accept="accept" @delete="deletePic" @afterRead="afterRead" name="3"
			:multiple="watermark?false:true" :maxCount="maxCount" accept="image" capture="camera"
			:previewFullImage="true" :width="width" :height="height" :deletable="deletable">
			<!-- 自定义上传样式 -->
			<image src="/static/home/bg.png" mode="scaleToFill" :style="{ width: width, height: height }"></image>
		</u-upload>
		<view class="ec-box" v-else>
			<image v-for="(v, i) in fileList" :key="i" @click="previewImg" :style="{ width: width, height: height }"
				:src="v.url" mode="scaleToFill">
			</image>
		</view>
		<view style="position: absolute;top: -99999px;" v-for="item in imgLength" :key="item">
			<canvas :id="'watermarkCanvas'+(item)" :canvas-id="'watermarkCanvas'+(item)"
				:style="'width: 750rpx; height:' +imgHeight+'rpx;'"></canvas>
		</view>
	</view>
</template>

<script>
	export default {
		props: {
			// 上传文件格式 video
			accept: {
				default: 'image',
				type: String
			},
			// 最多上传数
			maxCount: {
				default: 1,
				type: Number | String
			},
			// 宽度
			width: {
				default: '200rpx',
				type: Number | String
			},
			// 高度
			height: {
				default: '200rpx',
				type: Number | String
			},
			// 文件字段 使用时加上.sync  file.sync
			file: {
				default: () => [],
				type: Array | String
			},
			// 是否能删除
			deletable: {
				default: true,
				type: Boolean
			},
			// 回显模式(不能修改)
			echo: {
				default: false,
				type: Boolean
			},
			// 开启画水印
			watermark: {
				default: false,
				type: Boolean
			},
			projectName: {
				default: '名称',
				type: String
			}
		},
		data() {
			return {
				fileList: [],
				imgLength: 0,
				complete: true,
				imgHeight: 0,
			}
		},
		watch: {
			file: {
				handler(newValue) {
					this.handleImg(newValue)
					this.imgLength = this.fileList.length
				}
			}
		},
		mounted() {
			// if (this.file) {
			// 	this.handleImg(this.file)
			// }
		},
		methods: {
			addWatermark(filePath, index) {
				const rpx = uni.getSystemInfoSync().windowWidth / 750
				console.log(index, 'index');
				return new Promise(async (resolve1, reject1) => {

					// 首先将图片绘制到canvas上  
					const img = await new Promise((resolve, reject) => {
						uni.getImageInfo({
							src: filePath,
							success: function(info) {
								console.log(info, 'info');
								resolve(info);
							}
						});
					});
					const width = 750 * rpx; // canvas宽度  
					const height = 450 * rpx; // canvas高度 
					const imgHeight = img.height / (img.width / 750) * rpx
					this.imgHeight = img.height / (img.width / 750)
					const ctx = uni.createCanvasContext('watermarkCanvas' + index, this); // 假设你有一个canvas标签
					ctx.drawImage(img.path, 0 * rpx, 0 * rpx, width, imgHeight);


					// 接下来添加水印  


					// logobg
					ctx.setFillStyle('rgba(255,255,255,1)')
					ctx.fillRect(0 * rpx, imgHeight - (135 * rpx), 90 * rpx, 50 * rpx)

					// 添加logo  
					const logoPath = '/static/tabbar/cavLog.png'; // 假设logo在static目录下  
					ctx.drawImage(logoPath, 5 * rpx, imgHeight - 120 * rpx, 80 * rpx, 20 *
						rpx); // 在右下角添加logo  


					ctx.setFillStyle('rgba(106, 190, 113,1)')
					ctx.fillRect(90 * rpx, imgHeight - (135 * rpx), 160 * rpx, 50 * rpx)


					ctx.setFontSize(16 * rpx);
					ctx.setFillStyle('rgba(255,255,255,1)'); // 半透明水印  
					const projectText = this.projectName;
					if (projectText.length > 9) {
						let projectText1 = projectText.substring(0, 9)
						let projectText2 = projectText.substring(9)
						let projectTextList = [projectText1, projectText2]
						projectTextList.forEach((v, i) => {
							ctx.fillText(v, 100 * rpx, imgHeight - (115 * rpx) + i * 10); // 在图片上
						})

					} else {
						ctx.fillText(projectText, 100 * rpx, imgHeight - (105 * rpx)); // 在图片上
					}

					// 添加背景
					ctx.setFillStyle('rgba(226, 228, 227,1)')
					ctx.fillRect(0 * rpx, imgHeight - 90 * rpx, 250 * rpx, 90 * rpx)
					// 添加时间
					ctx.setFillStyle('rgba(000, 000, 000,1)');
					ctx.setFontSize(16 * rpx);
					const watermarkTime = '拍摄时间: ' + this.$fn.parseTime(new Date())
					ctx.fillText(watermarkTime, 10 * rpx, imgHeight - 70 * rpx); // 在图片上  

					// 添加姓名
					const watermarkPerson = '拍摄人员: ' + (uni.getStorageSync('userName') ? uni.getStorageSync(
						'userName') : '用户')
					ctx.fillText(watermarkPerson, 10 * rpx, imgHeight - 50 * rpx); // 在图片上  


					// 获取定位
					let addressInfo = ''
					const that = this

					function getLocationFn() {
						uni.getLocation({
							type: 'gcj02',
							altitude: true,
							isHighAccuracy: true,
							success: (res) => {
								console.log(res, '获取到经纬度信息');
								let location = [res.longitude, res.latitude].join(',')
								that.$amapFun.getRegeo({
									location,
									success: (data) => {
										//成功回调
										console.log(data, '获取到具体位置信息');
										addressInfo = data[0].regeocodeData
											.addressComponent.city + data[0]
											.regeocodeData.addressComponent
											.district

										finish()
									},
									fail: (info) => {
										//失败回调
										console.log(info)
										if (info.errCode == '10044') {
											uni.showToast({
												icon: 'none',
												title: '地理位置每日查询超过限制'
											})
										}
									}
								})
							},
							fail: (err) => {
								console.log('我没办法获取定位', err);
								that.$fn.getSetting()
							}
						});
					}

					getLocationFn()



					const finish = () => {
						// 地点
						const watermarkAddress = '地      点: ' + addressInfo + '·隆恩建工'
						if (watermarkAddress.length > 21) {
							let watermarkAddress1 = watermarkAddress.substring(0, 21)
							let watermarkAddress2 = watermarkAddress.substring(21)
							let watermarkAddressList = [watermarkAddress1, watermarkAddress2]
							// 旋转画布，参数为弧度，45度转换为弧度是 Math.PI / 4
							watermarkAddressList.forEach((v, i) => {
								ctx.fillText(v, 10 * rpx, imgHeight - (30 - i * 20) * rpx); // 在图片上
							})
						} else {
							ctx.fillText(watermarkAddress, 10 * rpx, imgHeight - 30 * rpx); // 在图片上
						}

						ctx.draw(true, setTimeout(_ => {
							// 将canvas转为图片  
							uni.canvasToTempFilePath({
								canvasId: 'watermarkCanvas' + index,
								success: function(res) {
									console.log(res.tempFilePath,'画完后的图片'); // 水印图片的路径  
									// 你可以将这个路径用于上传等后续操作  
									resolve1(res.tempFilePath)
								},
								fail: function(err) {
									reject1(err)
									uni.showToast({
										icon: 'none',
										title: '网络异常,请稍后再试~'
									})
								}
							}, this);

						}));
					}
				})
			},











			// 处理图片格式
			handleImg(newValue) {
				// console.log('newValue',newValue);
				if (typeof newValue == "object") {
					this.fileList = newValue.map(v => {
						return {
							url: this.vuex_imgUrl + v
						}
					}) || []
				} else {
					console.log('222');
					this.fileList = [{
						url: this.vuex_imgUrl + newValue
					}]
				}
				console.log('this.fileList', this.fileList);
			},
			// 删除图片
			deletePic(e) {
				console.log('e', e);
				this.fileList.splice(e.index, 1)
				let arr = this.fileList.map((v, i) => v.url.fileName || v.url.replace(this.vuex_imgUrl, ""))
				if (arr.length == 1) {
					[arr] = arr
				}
				console.log('arr', arr);
				this.$emit("update:file", arr)

			},
			// 新增图片
			async afterRead(event) {
				this.complete = false
				console.log("event", event);
				if (this.watermark) {
					this.imgLength = this.imgLength + 1
				}


				// 当设置 multiple 为 true 时, file 为数组格式，否则为对象格式
				let lists = [].concat(event.file)
				let fileListLen = this.fileList.length
				this.length = lists.length
				// await lists.map(async (item) => {
				// 	console.log('123');
				// 	item.url = await this.addWatermark(item.url)
				// 	console.log('234');
				// 	this.fileList.push({
				// 		...item,
				// 		status: 'uploading',
				// 		message: '上传中'
				// 	})
				// 	console.log('345');
				// })

				for (let [index, item] of lists.entries()) {
					if (this.watermark) {
						item.url = await this.addWatermark(item.url, this.fileList.length + index);
					}
					this.fileList.push({
						...item,
						status: 'uploading',
						message: '上传中'
					});

				}

				for (let i = 0; i < lists.length; i++) {
					const result = await this.uploadFilePromise(lists[i].url)
					let item = this.fileList[fileListLen]
					this.fileList.splice(fileListLen, 1, Object.assign(item, {
						status: 'success',
						message: '',
						url: result
					}))
					fileListLen++
				}

				console.log('this.fileList', this.fileList);
				let arr = this.fileList.map((v, i) => v.url.fileName || v.url.replace(this.vuex_imgUrl, ""))
				if (arr.length == 1) {
					[arr] = arr
				}
				console.log('arr', arr);
				this.$emit("update:file", arr)
				this.complete = true
			},
			// 上传图片
			uploadFilePromise(url) {
				return new Promise((resolve, reject) => {
					let a = uni.uploadFile({
						url: this.vuex_baseUrl + '/common/upload',
						filePath: url,
						name: 'file',
						formData: {
							user: 'test'
						},
						success: (res) => {
							// console.log('res', res);
							setTimeout(() => {
								resolve(JSON.parse(res.data))
							}, 1000)
						}
					});
				})
			},
			// 图片预览
			previewImg() {
				uni.previewImage({
					urls: this.fileList.map(v => v.url)
				})
			}
		}
	}
</script>

<style lang="scss" scoped>
	::v-deep .u-upload__wrap__preview {
		margin: 0;
	}

	.ec-box {
		display: flex;
		align-items: center;
		flex-wrap: wrap;

		image {
			// border: 1rpx solid red;
			margin-right: 10rpx;
			margin-bottom: 10rpx;
		}
	}
</style>